package Com.Ring.TradingMobile;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import Com.Ring.TradingMobile.Lib.Common;
import Com.Ring.TradingMobile.Lib.RET_CODE;
import Com.Ring.TradingMobile.Lib.Session;
import Com.Ring.TradingMobile.Object.CashBalances;
import Com.Ring.TradingMobile.Service.WebService;
import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class SoDuTienActivity extends Activity {

	private Button btn_Buy;
	private Button btn_Sell;
	private Button btn_StockBalance;

	private Button btn_Back;
	private Button btn_Home;
	private TextView lblGainLoss;
	private LinearLayout layout_Header;
	private LinearLayout layout_Content;
	private TextView lblTaiKhoanTextView;

	private int[] StrHeaderId = new int[]{R.string.str_WithDraw,
			R.string.str_T1, R.string.str_T2, R.string.str_T3,
			R.string.str_BuyToday, R.string.str_SellToday, R.string.str_Given,
			R.string.str_Used, R.string.str_MoneyAvailability};

	private String TAG = "SoDuTienActivity";
	private String StrGrainLoss = "";
	private CashBalancesAsync cashBalancesAsync;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sodutien);
		InitControlId();
		/*List<CashBalances> listCashBalances = GetCashBalance(Session.subCustAccounts
				.get(0));
		GetCashBalance_GainLoss(Session.subCustAccounts.get(0));
		ShowViewCashBalancess(listCashBalances);*/
		
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
		lblGainLoss.setText("");
		LoadCashBalances();
	}

	@Override
	protected void onStop() {
		super.onStop();
		CancelLoadCashBalances();
	}

	/*
	 * Writer by Huu_Nhan
	 */
	private void InitControlId() {
		btn_Back = (Button) findViewById(R.id.btnBack);
		btn_Buy = (Button) findViewById(R.id.btn_Mua);
		btn_StockBalance = (Button) findViewById(R.id.btn_SoDuCK);
		btn_Home = (Button) findViewById(R.id.btnHome);
		btn_Sell = (Button) findViewById(R.id.btn_Ban);
		lblGainLoss = (TextView) findViewById(R.id.lblGainLoss);
		layout_Header = (LinearLayout) findViewById(R.id.linearHeader);
		layout_Content = (LinearLayout) findViewById(R.id.linearContent);
		lblTaiKhoanTextView = (TextView) findViewById(R.id.lblTaiKhoan);
		lblTaiKhoanTextView.setText("TK: " + Session.subCustAccounts.get(0));

		TableLayout tableHeader = new TableLayout(this);
		TableRow[] rowsHeader = new TableRow[StrHeaderId.length];
		TextView[] txtHeader = new TextView[StrHeaderId.length];
		for (int i = 0; i < txtHeader.length; i++) {
			rowsHeader[i] = new TableRow(this);
			txtHeader[i] = new TextView(this);
			txtHeader[i].setText(StrHeaderId[i]);
			txtHeader[i].setHeight(30);
			txtHeader[i].setTextSize(12);
			txtHeader[i]
					.setBackgroundResource(R.drawable.border_color_textview);
			txtHeader[i].setTextColor(getResources()
					.getColor(R.color.title_row));
			rowsHeader[i].addView(txtHeader[i]);
			rowsHeader[i].setPadding(5, 1, 1, 1);
			tableHeader.addView(rowsHeader[i]);
		}
		layout_Header.addView(tableHeader);

		InitControlListen();
	}

	private void InitControlListen() {
		btn_StockBalance.setOnClickListener(new OnClickListener() {
			// @Override
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						SoDuCKActivity.class);
				startActivity(intent);
				finish();
			}
		});

		btn_Home.setOnClickListener(new OnClickListener() {

			// @Override
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						TradingMobileLoggedActivity.class);
				startActivity(intent);
				finish();
			}
		});
		btn_Back.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				finish();
			}
		});
		
		btn_Buy.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						MuaActivity.class);
				startActivity(intent);
				finish();
			}
		});
		btn_Sell.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						BanActivity.class);
				startActivity(intent);
				finish();
			}
		});
	}



	private void ShowViewCashBalancess(List<CashBalances> listCashBalances) {
		try {
			if (listCashBalances != null && listCashBalances.size() > 0) {
				layout_Content.removeAllViewsInLayout();
				String text = null;
				for (CashBalances balances : listCashBalances) {
					TableLayout tableContent = new TableLayout(
							SoDuTienActivity.this);
					TableRow[] rowContents = new TableRow[StrHeaderId.length];
					TextView[] txtContent = new TextView[StrHeaderId.length];
					for (int i = 0; i < txtContent.length; i++) {
						rowContents[i] = new TableRow(SoDuTienActivity.this);
						txtContent[i] = new TextView(SoDuTienActivity.this);
						// set text
						switch (i) {
							case 0 :
								text = balances.WithDraw;
								break;
							case 1 :
								text = balances.T1;
								break;
							case 2 :
								text = balances.T2;
								break;
							case 3 :
								text = balances.T3;
								break;
							case 4 :
								text = balances.TotalBuy;
								break;
							case 5 :
								text = balances.TotalSell;
								break;
							case 6 :
								text = balances.Given;
								break;
							case 7 :
								text = balances.Used;
								break;
							case 8 :
								text = balances.BuyCredit;
								break;

						}
						txtContent[i].setText(text);
						txtContent[i].setHeight(30);
						txtContent[i].setTextSize(12);
						txtContent[i].setGravity(Gravity.RIGHT);
						txtContent[i].setPadding(0, 0, 2, 0);
						LayoutParams layout = new LayoutParams(
								LayoutParams.WRAP_CONTENT,
								LayoutParams.WRAP_CONTENT);
						// layout.width = 50;

						txtContent[i]
								.setBackgroundResource(R.drawable.border_color_textview);
						rowContents[i].setPadding(1, 1, 1, 1);
						rowContents[i].addView(txtContent[i], layout);
						tableContent.addView(rowContents[i]);
					}
					// add row virtual
					TableRow rowVirtual = new TableRow(SoDuTienActivity.this);
					tableContent.addView(rowVirtual);
					//
					layout_Content.addView(tableContent);
				}
			}
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
	}

	private void GetCashBalance_GainLoss(String subAccount) {
		int accountType = Common.ACCOUNT.GetAccountType(subAccount);
		SoapObject request = new SoapObject(WebService.NAMESPACE,
				WebService.GetPortfolio);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		PropertyInfo parAccountNo = new PropertyInfo();
		parAccountNo.setName("accountNo");
		parAccountNo.setValue(subAccount);
		parAccountNo.setNamespace(WebService.NAMESPACE);

		PropertyInfo parPageNumber = new PropertyInfo();
		parPageNumber.setName("pageNumber");
		parPageNumber.setValue(1);
		parPageNumber.setNamespace(WebService.NAMESPACE);

		PropertyInfo parPageSize = new PropertyInfo();
		parPageSize.setName("pageSize");
		parPageSize.setValue(integer.config_shortAnimTime);
		parPageSize.setNamespace(WebService.NAMESPACE);

		PropertyInfo parAccountType = new PropertyInfo();
		parAccountType.setName("accountType");
		parAccountType.setValue(accountType);
		parAccountType.setNamespace(WebService.NAMESPACE);

		PropertyInfo parIsFirstTime = new PropertyInfo();
		parIsFirstTime.setName("isFirstTime");
		parIsFirstTime.setValue(Session.isFirstTime);
		Session.isFirstTime = true;
		parIsFirstTime.setNamespace(WebService.NAMESPACE);

		PropertyInfo parPosition = new PropertyInfo();
		parPosition.setName("position");
		parPosition.setValue(1);
		parPosition.setNamespace(WebService.NAMESPACE);

		request.addProperty(parAccountNo);
		request.addProperty(parPageNumber);
		request.addProperty(parPageSize);
		request.addProperty(parAccountType);
		request.addProperty(parIsFirstTime);
		request.addProperty(parPosition);

		envelope.setOutputSoapObject(request);
		HttpTransportSE http = new HttpTransportSE(
				WebService.ADDRESS_ETRADE_SERVICE);
		String soapAction = WebService.NAMESPACE + WebService.GetPortfolio;

		try {
			LinkedList<HeaderProperty> getSession = Session.GetSession();
			List<HeaderProperty> respHeaders = http.call(soapAction, envelope,
					getSession);
			if (respHeaders != null) {
				Session.SetSession(respHeaders);
			} else
				return;
			JSONObject resultsObj = new JSONObject(envelope.getResponse()
					.toString());
			int retCode;
			if (resultsObj != null) {
				retCode = resultsObj.getInt("RetCode");
				if (retCode == RET_CODE.SUCCESS.Value) {
					StrGrainLoss = resultsObj.getJSONObject("Result")
							.getJSONObject("SumInPage").getString("GainLoss");
					
				}
			}
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
	}

	private List<CashBalances> GetCashBalance(String subAccount) {
		List<CashBalances> listData = new ArrayList<CashBalances>();
		int accountType = Common.ACCOUNT.GetAccountType(subAccount);
		SoapObject request = new SoapObject(WebService.NAMESPACE,
				WebService.GetCashBalance);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		PropertyInfo parAccountNo = new PropertyInfo();
		parAccountNo.setName("accountNo");
		parAccountNo.setValue(subAccount);
		parAccountNo.setNamespace(WebService.NAMESPACE);

		PropertyInfo parAccountType = new PropertyInfo();
		parAccountType.setName("accountType");
		parAccountType.setValue(accountType);
		parAccountType.setNamespace(WebService.NAMESPACE);

		request.addProperty(parAccountNo);
		request.addProperty(parAccountType);

		envelope.setOutputSoapObject(request);
		HttpTransportSE http = new HttpTransportSE(
				WebService.ADDRESS_ETRADE_SERVICE);
		String soapAction = WebService.NAMESPACE + WebService.GetCashBalance;

		try {
			LinkedList<HeaderProperty> getSession = Session.GetSession();
			List<HeaderProperty> respHeaders = http.call(soapAction, envelope,
					getSession);
			if (respHeaders != null) {
				Session.SetSession(respHeaders);
			} else
				return listData;
			JSONObject resultsObj = new JSONObject(envelope.getResponse()
					.toString());
			int retCode;
			if (resultsObj != null) {
				retCode = resultsObj.getInt("RetCode");
				if (retCode == RET_CODE.SUCCESS.Value) {
					JSONObject stockBalances = resultsObj
							.getJSONObject("Result");
					CashBalances balances = new CashBalances();
					balances.BuyCredit = stockBalances
							.getString(CashBalances.PropertyString.BuyCredit
									.toString());
					balances.WithDraw = stockBalances
							.getString(CashBalances.PropertyString.WithDraw
									.toString());
					balances.TotalBuy = stockBalances
							.getString(CashBalances.PropertyString.TotalBuy
									.toString());
					balances.T1 = stockBalances
							.getString(CashBalances.PropertyString.AMT_T1
									.toString());
					balances.T2 = stockBalances
							.getString(CashBalances.PropertyString.AMT_T2
									.toString());
					balances.T3 = stockBalances
							.getString(CashBalances.PropertyString.AMT_T3
									.toString());
					balances.TotalSell = stockBalances
							.getString(CashBalances.PropertyString.TotalSell
									.toString());
					balances.Given = stockBalances
							.getString(CashBalances.PropertyString.AppCreditLine
									.toString());
					balances.Used = stockBalances
							.getString(CashBalances.PropertyString.UsedCreditLine
									.toString());
					listData.add(balances);
				}
			}
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
		return listData;
	}
	private void CancelLoadCashBalances() {
		if(cashBalancesAsync!=null) {
			cashBalancesAsync.cancel(true);
			cashBalancesAsync=null;
		}
	}
	
	private void LoadCashBalances() {
		CancelLoadCashBalances();
		cashBalancesAsync = new CashBalancesAsync();
		cashBalancesAsync.execute(Session.subCustAccounts.get(0));
	}
	private class CashBalancesAsync extends AsyncTask<String, List<CashBalances>, List<CashBalances>>{

		@Override
		protected List<CashBalances> doInBackground(String... params) {
			List<CashBalances> cashBalance = GetCashBalance(params[0]);
			publishProgress(cashBalance);
			GetCashBalance_GainLoss(params[0]);
			return cashBalance;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(List<CashBalances> result) {
			if(StrGrainLoss!="") {
				lblGainLoss.setText(Common.FormatNumber(Double.parseDouble(StrGrainLoss))+" VND");
				double gainLossDouble = Double.parseDouble(StrGrainLoss);
				if (gainLossDouble > 0) {
					lblGainLoss.setTextColor(getResources().getColor(
							R.color.up));
				} else if (gainLossDouble < 0) {
					lblGainLoss.setTextColor(getResources().getColor(
							R.color.down));
				} else {
					lblGainLoss.setTextColor(getResources().getColor(
							R.color.nochange));
				}
			}
			StrGrainLoss="";
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(List<CashBalances>... values) {
			ShowViewCashBalancess(values[0]);
		}
		
	}
}
